package com.itheima.auth;


import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;


import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * company: www.abc.com
 * Author: 29746
 * Create Data: 2020/11/21
 */
@Component
public class MyUserDetailsService implements UserDetailsService {

    @Resource
    private PasswordEncoder passwordEncoder;

    private Map<String, Map<String,String>> users=new HashMap<>();

    private boolean inited=false;

    private void initUsers(){//真实数据应该是由数据库查出来，这里只是用map模拟用户
        if (inited==false){
            HashMap<String, String> user1 = new HashMap<>();
            user1.put("username","user1");
            user1.put("password",passwordEncoder.encode("1234"));
            user1.put("authority","ROLE_USER1,user1");

            HashMap<String, String> user2 = new HashMap<>();
            user2.put("username","user2");
            user2.put("password",passwordEncoder.encode("1234"));
            user2.put("authority","ROLE_USER2");

            users.put("user1",user1);
            users.put("user2",user2);
            inited=true;
        }
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        initUsers();
        Map<String, String> user = users.get(username);
        if (user==null){
            return new User(username,"",
                    AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_USER"));
        }
        return new User(username,user.get("password"),
                AuthorityUtils.commaSeparatedStringToAuthorityList("authority"));
    }
}
